package sistemadeproyectos;

import java.sql.*;
import org.postgresql.Driver;

public class BDAdmin {

    private String query;
    private ResultSet rs = null;
    private Statement smt = null;
    private Connection conn = null;
    private ServersConf rutas = new ServersConf();
    
    public BDAdmin(String query){
        this.query = query;
    }
    
    /**
     * @param query the query to set
     */
    public void setQuery(String query) {
        this.query = query;
    }
    
    public ResultSet consulta(){
        String driver = "org.postgresql.Driver"; //Nombre del driver PostgreSQL
        String connectString = "jdbc:postgresql://" + this.rutas.getIPBD() + ":" + this.rutas.getPuertoBD() +"/Proyectos/"; //URL de la Base de Datos
        String user = "postgres"; //Usuario de PostgreSQL
        String password = "12345"; //Clave de la Base de Datos
        
        try{
            Class.forName(driver);
            conn = DriverManager.getConnection(connectString, user, password);
            smt = conn.createStatement();
            rs = smt.executeQuery(this.query);
        }
        catch (ClassNotFoundException cnfe){
            cnfe.printStackTrace();
        }
        catch(SQLException sqle){
            sqle.printStackTrace();
        }
        return rs;
    }
    
    public void actualizar(){
        String driver = "org.postgresql.Driver"; //Nombre del driver PostgreSQL
        String connectString = "jdbc:postgresql://" + this.rutas.getIPBD() + ":" + this.rutas.getPuertoBD() +"/Proyectos/"; //URL de la Base de Datos
        String user = "postgres"; //Usuario de PostgreSQL
        String password = "12345"; //Clave de la Base de Datos
        try{
            Class.forName(driver);
            conn = DriverManager.getConnection(connectString, user, password);
            PreparedStatement ps = conn.prepareStatement(this.query);
            ps.executeUpdate();            
        }
        catch (ClassNotFoundException cnfe){
            cnfe.printStackTrace();
        }
        catch(SQLException sqle){
            sqle.printStackTrace();
        }
    }
    
    public void cerrar(){
        try {
            if (this.rs != null){ 
                this.rs.close();
            }
            if (this.smt != null){ 
                this.smt.close();
            }
            if (this.conn != null){ 
                this.conn.close();
            }
        }
        catch (SQLException esql){
            System.out.println(esql.getMessage());
        }
    }
}
